package org.hanbo.code.repository.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.hanbo.code.repository.exception.CodeSnippetsListNotFoundException;
import org.hanbo.code.repository.exception.ErrorDescription;
import org.hanbo.code.repository.persistence.entity.CodeSnippet;
import org.hanbo.code.repository.persistence.entity.CodeSnippetDAO;

public class RetrieveUserOwnCodeSnippetsAction
	extends CodeSnippetListViewActionBase implements ServletRequestAware
{
	private static final long serialVersionUID = -3804849467806140824L;
	private HttpServletRequest servletReq;
	
	@Override
	public void setServletRequest(HttpServletRequest arg0)
	{
		servletReq = arg0;
	}

	public String execute()
	{
		String retStatus = super.execute();
		if (!super.getSuperActionSuccessful())
		{
			return retStatus;
		}
		
		try
		{
			if(servletReq != null)
			{
				int snippetsCount = parseCodeSnippetCount(servletReq);
				String authorEmail = this.getLoggedInUser().getEmail();
				
				CodeSnippetDAO codeSnippetRetriever = new CodeSnippetDAO();
				try
				{
					codeSnippetRetriever.acquirePersistenceManager();
					List<CodeSnippet> snippetsList = codeSnippetRetriever.findAllSnippetsByAuthorEmail(
						authorEmail, 0, snippetsCount
					);
					if (snippetsList == null)
					{
						throw new CodeSnippetsListNotFoundException("Your own");
					}
					
					this.setRetrievedCodeSnippets(
						CodeSnippetListItem.createListOfCodeSnippetsForTable(snippetsList)
					);
					
					return SUCCESS;
				}
				catch (Exception e)
				{
					throw e;
				}
				finally
				{
					codeSnippetRetriever.releasePersistenceManager();
				}
			}
			else
			{
				throw new IllegalArgumentException("Servlet request is null. Impossible...");
			}
		}
		catch(CodeSnippetsListNotFoundException e)
		{
			super.setErrorDescription(new ErrorDescription(e));
			return ERROR;
		}
		catch(Exception e)
		{
			super.setErrorDescription(new ErrorDescription(1000, e));
			return ERROR;
		}
	}
	
	public String getSubjectField()
	{
		return "Your own Code Snippets";
	}
}
